package com.utils.aes.convert;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.utils.aes.Aes;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Objects;
import java.util.Optional;

/**
 * 用于 JSON 序列化和反序列化， @JSONField(serializeUsing = AesLongJsonConvert.Serializer.class, deserializeUsing = AesLongJsonConvert.Deserializer.class)
 *
 * @author 谢长春 2022-02-06
 */
@Slf4j
public class AesLongJsonConvert {

    public static class Serializer implements ObjectSerializer {

        @Override
        public void write(JSONSerializer serializer, Object value, Object fieldName, Type fieldType, int features) throws IOException {
            if (Objects.isNull(value)) {
                return;
            }
            if (log.isDebugEnabled()) {
                log.debug("加密:{}:{}", fieldName, value);
            }
            serializer.write(Aes.encrypt(Objects.toString(value)));
        }
    }

    @Slf4j
    public static class Deserializer implements ObjectDeserializer {
        @SuppressWarnings({"unchecked"})
        @Override
        public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
            final String value = parser.getLexer().stringVal();
            if (log.isDebugEnabled()) {
                log.debug("解密:{}:{}", fieldName, value);
            }
            return (T) Optional.ofNullable(Aes.decrypt(value)).map(Long::parseLong).orElse(null);
        }

        @Override
        public int getFastMatchToken() {
            return 0;
        }
    }

}
